/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package tools;

import tools.cryptage.ICryptage;
import tools.cryptage.FacadeSha1;
import tools.cryptage.FacadeBCrypt;
import tools.cryptage.BCrypt;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HashMap;

/**
 *
 * @author coload12
 */
public class Tools {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException, IOException {
        // TODO code application logic here
        System.exit(0);
        
        System.out.println (Tools.generateToken());
        System.out.println (Tools.generateToken());
        System.out.println (Tools.generateToken());
        System.out.println (Tools.generateToken());
        System.out.println (Tools.generateToken());
        System.out.println (Tools.generateToken());
        System.exit(0);
        
        
        String salt = BCrypt.gensalt();
        ICryptage sha1 = new FacadeSha1();
        String password = "beignet";
        String hash = sha1.cryptage(password, salt);
        System.out.println("Hash => " + hash);
        System.out.println("SHA1 --");
        findHash(hash, salt, sha1);
        HashMap<String, String> rainbow = buildRainbowTable(salt, sha1);
        System.out.println(rainbow.size());

        ICryptage bcrypt = new FacadeBCrypt();
        hash = bcrypt.cryptage(password, salt);
        System.out.println("Hash => " + hash);
        System.out.println("BCRYPT --");
        //findHash(hash, salt, bcrypt);
        rainbow = buildRainbowTable(salt, bcrypt);
        System.out.println("Construction de la rainbow table terminé");
        findHash(hash, rainbow);
    }

    public static HashMap<String, String> buildRainbowTable(String salt, ICryptage crypteur) throws IOException {
        HashMap<String, String> rainbow = new HashMap<String, String>();
        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("DicFra.csv")));
        String ln = "";
        long cpt = 0;
        while ((ln = in.readLine()) != null) {
            String mot = ln.split(",")[0].substring(1, ln.split(",")[0].length() - 1);
            rainbow.put(crypteur.cryptage(mot, salt), mot);
        }
        in.close();
        return rainbow;
    }

    public static void findHash(String hash, String salt, ICryptage crypteur) throws FileNotFoundException, IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("DicFra.csv")));
        String ln = "";
        long cpt = 0;
        while ((ln = in.readLine()) != null) {
            if (cpt == 100) {
                cpt = 0;
                // System.out.println ("100 mots ont été essayé");
            }
            String mot = ln.split(",")[0].substring(1, ln.split(",")[0].length() - 1);

            if (crypteur.valider(mot, salt, hash)) {
                System.out.println("Mot :" + mot);
                break;
            }
            cpt++;
        }
        in.close();
    }

    public static void findHash(String hash, HashMap<String, String> rainbow) throws FileNotFoundException, IOException {
        String password = rainbow.get(hash);
        System.out.println("Mot: " + password);
    }

    public static String chiffrer(String password, String salt) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        String hashed = BCrypt.hashpw(password, salt);
        return hashed;
    }

    public static boolean valider(String mot, String hash) {
        return toSHA1(toSHA1((mot).getBytes()).getBytes()).equals(hash);
        //return BCrypt.checkpw(mot, hash);
    }

    public static String byteArrayToHexString(byte[] b) {
        String result = "";
        for (int i = 0; i < b.length; i++) {
            result
                    += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
        }
        return result;
    }

    public static String toSHA1(byte[] convertme) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return byteArrayToHexString(md.digest(convertme));
    }

    public static void genererMotPasse(int nb_motpasse, String nom_fichier, ICryptage crypteur) throws FileNotFoundException, IOException {
        PrintWriter fichier = new PrintWriter(new FileOutputStream(nom_fichier));
        for (int cpt = 0; cpt < nb_motpasse; cpt++) {
            String salt = crypteur.gensalt();
            fichier.println(crypteur.cryptage("azerty", salt) + ";" + salt);
        }
        fichier.close();
    }

    public static void ecrireInsertIntoClient(ICryptage crypteur) throws FileNotFoundException, IOException {
        PrintWriter out = new PrintWriter(new FileOutputStream("client.sql"));
        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("client.csv")));
        String ln = "";
        long cpt = 0;
        while ((ln = in.readLine()) != null) {

            String[] cellules = ln.split(";");
            String nom        = cellules[0];
            String prenom     = cellules[1];
            String email      = nom + "." + prenom + "@gmail.com";
            String ville      = "PARIS";
            String etat       = "0";
            String salt       = crypteur.gensalt();
            String motpasse   = crypteur.cryptage("azerty", salt);
            String first_otp  = "12345678";
            String last_otp   = "12345678";
                    
            String request    = "INSERT INTO client (nom,prenom,email,ville,etat,motpasse,salt,first_otp,last_otp) VALUES (";
            request += "'" + nom + "',";
            request += "'" + prenom + "',";
            request += "'" + email + "',";
            request += "'" + ville + "',";
            request +=       etat +  ",";
            request += "'" + motpasse + "',";
            request += "'" + salt + "',";
            request += "'" + first_otp + "',";
            request += "'" + last_otp + "'";
            request += ");";
            out.println (request);
        }
        in.close();
        out.close();
    }
    
    public static String generateToken()
    {
        SecureRandom random = new SecureRandom();
        return new BigInteger(130, random).toString(32);
    }
    
    
}
